import * as React from 'react';
import { Form, Button, Modal, notification, } from 'antd';

import { ButtonType } from 'antd/lib/button';
import IForm from '../components/IForm';
import http from '../utils/http';
import validation from '../utils/validation';


interface IAppProps {
  form?: any,
  history?: any,
  postData?: any,
  name: string,
  postUrl: string,
  type: ButtonType,
  IFormData: any,
  IFormItems: any[],
  title: string
}


class ButtonForm extends React.Component<IAppProps, {}> {
  state = {
    visible: false,
    confirmLoading: false,
  };

  postData: any = {};

  private showModal = async (e: any) => {
    e.preventDefault();
    if (!!this.props.postData) {
      this.postData = await this.props.postData();
    }
    this.setState({
      visible: true,
    });
  };

  handleOk = async () => {

    this.setState({
      confirmLoading: true,
    });

    await new Promise((resolve) => setTimeout(resolve, 1000));
    const value = await validation.validateFields(this.props.form);
    this.setState({
      visible: false,
      confirmLoading: false,
    });

    await http.post(this.props.postUrl, {
      ...value,
      ...this.postData,
    });
    notification.success({
      message: "提交成功",
      duration: 2,
      onClose() {
        window.location.reload();
      }
    });

  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };


  public render() {
    const { visible, confirmLoading } = this.state;
    const { name, type } = this.props;
    return (
      <>
        <Button type={type} onClick={this.showModal.bind(this)}>
          {name}
        </Button>
        <Modal
          title="提交"
          okText='确认'
          cancelText='取消'
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}
        >
          <IForm
            {...this.props}
            data={this.props.IFormData}
            layout="inline"
            items={this.props.IFormItems} />
        </Modal>
      </>
    );
  }
}

const WrappedIButtonForm = Form.create({ name: 'ButtonForm' })(ButtonForm);

class IButtonForm extends React.Component<IAppProps, {}> {
  render() {
    return (
      <WrappedIButtonForm {...this.props} />
    );
  }
}


export default IButtonForm;